package com.java.jwt.interceptor.utils.utils;

import com.alibaba.fastjson.JSONObject;
import com.java.jwt.interceptor.utils.model.JwtUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;

/**
 * Jwt工具类
 * <p>
 * 1、从token中获取用户信息；
 * 2、返回解析的用户信息。
 *
 * @author Wu Qingzhuang
 * @date 2021/06/15 9:58
 */
@Slf4j
public class JwtUtils {
    public static JwtUser parseToken(String token) {
        String tokenParse = token.replace("Bearer ", "");
        Jwt jwt = JwtHelper.decode(tokenParse);
        String claims = jwt.getClaims();
        JSONObject jwtClaims = JSONObject.parseObject(claims);
        JwtUser jwtUser = JwtUser.builder().build();
        if (StringUtils.isNotEmpty(jwtClaims.getString("user_name"))) {
            jwtUser.setUserCode(jwtClaims.getString("user_name"));
        }
        if (StringUtils.isNotEmpty(jwtClaims.getString("userId"))) {
            jwtUser.setUserId(Long.parseLong(jwtClaims.getString("userId")));
        }
        if (StringUtils.isNotEmpty(jwtClaims.getString("userName"))) {
            jwtUser.setUserName(jwtClaims.getString("userName"));
        }
        if (StringUtils.isNotEmpty(jwtClaims.getString("cityOrgCode"))) {
            jwtUser.setCityOrgCode(jwtClaims.getString("cityOrgCode"));
        }
        if (StringUtils.isNotEmpty(jwtClaims.getString("secondaryOrgId"))) {
            jwtUser.setSecondaryOrgId(Long.parseLong(jwtClaims.getString("secondaryOrgId")));
        }
        if (StringUtils.isNotEmpty(jwtClaims.getString("orgId"))) {
            jwtUser.setOrgId(Long.parseLong(jwtClaims.getString("orgId")));
        }
        if (StringUtils.isNotEmpty(jwtClaims.getString("orgName"))) {
            jwtUser.setOrgName(jwtClaims.getString("orgName"));
        }
        if (StringUtils.isNotEmpty(jwtClaims.getString("cityOrgId"))) {
            jwtUser.setCityOrgId(Long.parseLong(jwtClaims.getString("cityOrgId")));
        }
        if (StringUtils.isNotEmpty(jwtClaims.getString("cityOrgName"))) {
            jwtUser.setCityOrgName(jwtClaims.getString("cityOrgName"));
        }
        if (StringUtils.isNotEmpty(jwtClaims.getString("openId"))) {
            jwtUser.setOpenId(jwtClaims.getString("openId"));
        }
        if (StringUtils.isNotEmpty(jwtClaims.getString("relationId"))) {
            jwtUser.setRelationId(Long.parseLong(jwtClaims.getString("relationId")));
        }
        return jwtUser;
    }
}
